package com.ddtech.business.task.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ddtech.business.check.entity.Check;
import com.ddtech.business.check.service.CheckService;
import com.ddtech.business.check.vo.res.ResRank;
import com.ddtech.business.common.BaseService;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.task.entity.Task;
import com.ddtech.business.task.mapper.TaskMapper;
import com.ddtech.business.task.query.TaskQuery;
import com.ddtech.business.task.service.TaskCourseService;
import com.ddtech.business.task.service.TaskService;
import com.ddtech.business.task.service.TaskUserService;
import com.ddtech.business.task.vo.req.MyTaskCourseVo;
import com.ddtech.business.task.vo.req.TaskReqVo;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class TaskServiceImpl extends BaseService<TaskMapper, Task> implements TaskService {
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private TaskCourseService taskCourseService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CheckService checkService;
    @Resource
    private TaskMapper taskMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(TaskReqVo taskReqVo) {
        Task task = new Task();
        BeanUtil.copyProperties(taskReqVo, task, CopyOptions.create().setIgnoreCase(true));
        task.init();
        Integer duration = taskReqVo.getTaskCourse().stream().mapToInt(courseVo -> {
            Course course = courseService.getById(courseVo.getCourseId());
            return course.getClassHour();
        }).sum();
        task.setDuration(duration);
        task.setCreateBy(SecurityUtils.getName());
        this.saveOrUpdate(task);
        taskReqVo.setId(task.getId());
        taskUserService.saveTaskUser(taskReqVo);
        taskCourseService.saveTaskCourse(taskReqVo);
    }

    @Override
    public Object pageList(TaskQuery taskQuery) {
        IPage<Task> result = this.page(taskQuery.populatePage(), taskQuery.autoWrapper());
        List<Task> records = result.getRecords();
        List<TaskReqVo> collect = records.stream().map(item -> getTaskVo(item)).collect(Collectors.toList());
        return PageUtil.toPage(collect, result.getTotal());
    }

    @Override
    public void del(String id) {
        Task task = this.getById(id);
        BizPreconditions.check(task == null, BusinessEnum.QUERY_ERROR.getMsg());
        task.baseDelete();
        this.saveOrUpdate(task);
    }

    @Override
    public TaskReqVo info(String id) {
        Task task = this.getById(id);
        return getTaskVo(task);
    }

    @Override
    public Object getScheduleList(TaskQuery taskQuery) {
        IPage<Map<String, Object>> page = taskMapper.getScheduleList(taskQuery.populatePage(), taskQuery.getTaskName());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object getMyTask(IPage pageInfo, Integer isFinish) {
        IPage<Task> myTask = taskMapper.getMyTask(pageInfo, SecurityUtils.getUserId(), isFinish);
        List<Task> records = myTask.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(item -> item.setCourseList(
                    this.getData(SecurityUtils.getUserId(), item.getId())
            ));
        }
        return PageUtil.toPage(myTask.getRecords(), myTask.getTotal());
    }

    @Override
    public Object getScheduleCheckList(String taskId,String userName, IPage pageInfo){
        Task task = this.getById(taskId);
        BizPreconditions.check(task == null, BusinessEnum.QUERY_ERROR.getMsg());
        if(StringUtils.isNotBlank(task.getCheckId())){
            ResRank rank = checkService.getRank(task.getCheckId(), userName,pageInfo);
            return PageUtil.toPage(rank.getPagination().getRecords(), rank.getPagination().getTotal());
        }
        return null;
    }

    public List< MyTaskCourseVo> getData(String userId,String TaskId){
        List< MyTaskCourseVo > data = taskMapper.getMyTaskCourse(userId, TaskId);
        for(MyTaskCourseVo myTaskCourseVo:data){
            String file=myTaskCourseVo.getThemeImage();
            if(StringUtils.isNotEmpty(file)){
                JSONArray array = JSON.parseArray(file);
                if (array!=null){
                    JSONObject json =array.getJSONObject(0);
                    myTaskCourseVo.setThemeImage(json.getString("url"));
                }
            }
        }
        return  data;
    }


    public TaskReqVo getTaskVo(Task task) {
        TaskReqVo taskReqVo = new TaskReqVo();
        BeanUtil.copyProperties(task, taskReqVo);
        taskReqVo.setTaskCourse(taskCourseService.getCourse(task.getId()));
        taskReqVo.setTaskUser(taskUserService.getUser(task.getId()));
        if (StringUtils.isNoneBlank(task.getCheckId())) {
            Check check = checkService.getById(task.getCheckId());
            if (check != null) {
                taskReqVo.setCheckName(check.getCheckName());
            }
        }
        return taskReqVo;
    }

}
